<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {Avatar, Button, Card, Tag, Tooltip, Empty, Spin, message, Input, Form} from 'ant-design-vue';
import {LikeOutlined,
  MessageOutlined,
  StarOutlined,
  EyeOutlined,
  EditOutlined,
  LikeFilled,
  StarFilled,
  ReloadOutlined,
  BookOutlined
} from '@ant-design/icons-vue';
import router from '@/router';
import BlogVO = API.BlogVO;
import {collectBlog, likeBlog, listBlogByRecommend, listBlogVoByPage} from "@/api/blogController.ts";
import dayjs from "dayjs";
import {useLoginUserStore} from "@/stores/useLoginUserStore.ts";
import BlogQueryRequest = API.BlogQueryRequest;

// 模拟博客数据
const blogPosts = ref([
  {
    id: 1,
    title: '如何在Vue3中高效使用组合式API',
    content: '组合式API是Vue3的重要特性，它提供了更灵活的代码组织方式...',
    author: {
      name: '技术达人',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user1 '
    },
    publishTime: '2023-11-15 10:30',
    likes: 128,
    comments: 36,
    favorites: 42,
    views: 892,
    tags: ['Vue3', '组合式API', '前端开发']
  },
  {
    id: 2,
    title: 'React与Vue的性能对比分析',
    content: 'React和Vue都是流行的前端框架，但它们在性能表现上有哪些差异呢？本文将从多个维度进行深入分析...',
    author: {
      name: '框架对比师',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user2 '
    },
    publishTime: '2023-11-12 15:45',
    likes: 256,
    comments: 78,
    favorites: 96,
    views: 1254,
    tags: ['React', 'Vue', '性能优化']
  },
  {
    id: 3,
    title: 'TypeScript高级类型技巧分享',
    content: 'TypeScript的高级类型系统为我们提供了强大的类型检查能力，本文将分享一些实用的高级类型技巧...',
    author: {
      name: 'TS专家',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user3 '
    },
    publishTime: '2023-11-10 09:15',
    likes: 189,
    comments: 52,
    favorites: 63,
    views: 987,
    tags: ['TypeScript', '类型系统', '高级技巧']
  },
  {
    id: 4,
    title: '现代CSS布局技巧大全',
    content: 'CSS Grid和Flexbox的出现彻底改变了我们布局网页的方式，本文将介绍一些现代CSS布局的实用技巧...',
    author: {
      name: 'CSS大师',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user4 '
    },
    publishTime: '2023-11-08 14:20',
    likes: 324,
    comments: 89,
    favorites: 127,
    views: 1563,
    tags: ['CSS', 'Grid', 'Flexbox', '布局']
  }
]);

const loginUserStore = useLoginUserStore()
const blogList = ref<BlogVO[]>([])

// 模拟加载状态
const loading = ref(false);

// 搜索表单数据
const searchForm = ref<BlogQueryRequest>({
  searchText: ''
});

// 搜索函数（用户后续实现逻辑）
const handleSearch = async () => {
  //发请求
  // const res = await listBlogVoByPage(searchForm.value)
  // if(res.data.code === 0&& res.data.data){
  //   blogList.value = res.data.data.records
  //   //重置页码
  //   searchForm.value.current = 1
  // }else{
  //   message.error('获取数据失败，' + res.data.message)
  // }


  await fetchData()
  searchForm.value.current = 1


};

// 重置函数
const handleReset = async () => {
  searchForm.value = {
    searchText: ''
  };
  await fetchData();
};

// 跳转到博客详情页
const goToBlogDetail = (blogId: number) => {
  router.push(`/blog/${blogId}`);
};

// 跳转到新增博客页面
const goToAddBlog = () => {
  router.push('/blog/add');
};

// 模拟点赞功能
const handleLike = async (blog: BlogVO) => {
  const res = await likeBlog({
    blogId: blog.id,
    userId: loginUserStore.loginUser.id,
    isLiked: !blog.isLiked
  })
  if (res.data.code === 0 && res.data.data) {

    if (blog.isLiked) {
      blog.likeNum--;
      message.success("取消点赞成功")
    } else {
      blog.likeNum++;
      message.success("点赞成功")
    }
    blog.isLiked = !blog.isLiked;
    await fetchData(true)
  } else {
    message.error("点赞失败，" + res.data.message)
  }
};

// 收藏功能
const handleFavorite = async (blog: BlogVO) => {
  const res = await collectBlog({
    blogId: blog.id,
    userId: loginUserStore.loginUser.id,
    isCollected: !blog.isCollected
  })
  if (res.data.code === 0 && res.data.data) {
    if (blog.isCollected) {
      blog.collectNum--;
      message.success("取消收藏成功")
    } else {
      blog.collectNum++;
      message.success("收藏成功")
    }
    blog.isCollected = !blog.isCollected;
    await fetchData(true)
  } else {
    message.error("收藏失败，" + res.data.message)
  }
};

const fetchData = async (isRefresh: boolean = false) => {
  const res = await listBlogByRecommend({
    ...searchForm.value,
    isRefresh: isRefresh
  })
  if (res.data.code === 0 && res.data.data) {
    blogList.value = res.data.data.records
    console.log("获取博客成功，" + res.data.data)
    console.log(blogList.value)
  } else {
    message.error("获取博客失败")
  }
}
onMounted(async () => {
  await fetchData()

})
</script>

<template>
  <div id="BlogPage">
    <div class="blog-header">
      <h1 class="page-title">博客广场</h1>
      <a-button type="primary" @click="goToAddBlog">
        <template #icon>
          <EditOutlined/>
        </template>
        写博客
      </a-button>
    </div>

    <!-- 修改后的搜索区域 -->
    <div class="search-container">
      <Form layout="inline" :model="searchForm" @submit.prevent="handleSearch" class="search-form">
        <Form.Item>
          <Input
              v-model:value="searchForm.searchText"
              placeholder="从海量数据中搜索"
              allowClear
              class="search-input"
          />
        </Form.Item>

        <Form.Item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </Form.Item>

        <Form.Item>
          <Button @click="handleReset">重置</Button>
        </Form.Item>
      </Form>

      <a-button @click="fetchData(true)" :loading="loading" class="refresh-btn">
        <template #icon>
          <ReloadOutlined/>
        </template>
        刷新
      </a-button>
    </div>

    <div class="blog-content">
      <Spin v-if="loading" tip="加载中..." style="display: block; margin: 40px auto;"/>

      <div v-else-if="blogList.length === 0" class="empty-state">
        <div class="empty-icon">
          <BookOutlined />
        </div>
        <h3 class="empty-title">还没有博客内容呢</h3>
        <p class="empty-description">
          这里似乎还是一片空白，成为第一个分享想法的人吧！
        </p>
        <div class="empty-actions">
          <a-button type="primary" @click="goToAddBlog" size="large">
            <template #icon>
              <EditOutlined/>
            </template>
            写第一篇博客
          </a-button>
          <a-button @click="fetchData(true)" class="ml-4">
            <template #icon>
              <ReloadOutlined/>
            </template>
            再刷新试试
          </a-button>
        </div>
      </div>

      <div class="blog-list" v-else>
        <Card
            v-for="blog in blogList"
            :key="blog.id"
            hoverable
            class="blog-card"
            @click="goToBlogDetail(blog.id)"
        >

          <div class="blog-meta" @click.stop>
            <Avatar :src="blog.userVO.userAvatar"/>
            <span class="author-name">{{ blog.userVO.username }}</span>
            <span class="publish-time">{{ dayjs(blog.createTime).format(" YYYY-MM-DD HH:mm:ss ") }}</span>
          </div>

          <h3 class="blog-title">{{ blog.title }}</h3>

          <!--          <p class="blog-excerpt">{{ blog.content }}</p>-->
          <p class="blog-excerpt" v-html="blog.content"></p>

          <div class="blog-tags" @click.stop>
            <Tag v-for="tag in blog.tags" :key="tag" color="blue">
              {{ tag }}
            </Tag>
          </div>

          <div class="blog-stats" @click.stop>
            <Tooltip title="点赞">
              <div class="stat-item" @click="handleLike(blog)">
                <LikeOutlined v-if="!blog.isLiked"/>
                <LikeFilled v-else style="color: rgb(41, 110, 235)"/>
                <span>{{ blog.likeNum }}</span>
              </div>
            </Tooltip>

            <Tooltip title="评论">
              <div class="stat-item" @click="goToBlogDetail(blog.id)">
                <MessageOutlined/>
                <span>{{ blog.commentCount }}</span>
              </div>
            </Tooltip>

            <Tooltip title="收藏">
              <div class="stat-item" @click="handleFavorite(blog)">
                <StarOutlined v-if="!blog.isCollected"/>
                <StarFilled v-else style="color: rgb(255, 207, 71)"/>
                <span>{{ blog.collectNum }}</span>
              </div>
            </Tooltip>

            <Tooltip title="浏览">
              <div class="stat-item">
                <EyeOutlined/>
                <span>{{ blog.viewCount }}</span>
              </div>
            </Tooltip>
          </div>
        </Card>
      </div>
    </div>
  </div>
</template>

<style scoped>
#BlogPage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.blog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.blog-content {
  width: 100%;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.refresh-btn {
  margin-left: auto;
}

.search-input {
  width: 400px;
  height: 35px;
}

.skill-input {
  width: 200px;
}

/* 响应式设计 */
@media (min-width: 769px) {
  .search-container .ant-form-inline {
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }

  .refresh-btn {
    margin-left: 0;
    margin-top: 12px;
  }

  .search-container .ant-form-inline {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .search-container .ant-form-item {
    margin-bottom: 12px;
    width: 100%;
  }

  .search-input,
  .skill-input {
    width: 100%;
  }
}

.blog-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 24px;
}

.blog-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  position: relative;
}

.blog-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.blog-meta {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
  height: 32px; /* 固定高度 */
}

.author-name {
  margin-left: 8px;
  margin-right: 12px;
}

.publish-time {
  color: #999;
  font-size: 12px;
}

.blog-title {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  height: 30px; /* 固定高度，确保标题不会因为字数变化影响布局 */
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.blog-excerpt {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex-grow: 0; /* 不允许内容区域自动增长 */
  height: 72px; /* 固定高度 */
}

.blog-tags {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.blog-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  margin-top: auto; /* 确保在底部 */
  position: relative;
  bottom: 0;
  width: 100%;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s;
}

.stat-item:hover {
  color: #1890ff;
}

.stat-item span {
  margin-left: 4px;
}
  /* 生动的空状态样式 */
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
    background-color: white;
    border-radius: 12px;
    margin: 20px 0;
    min-height: 500px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
  
  .empty-icon {
    font-size: 80px;
    color: #f0f0f0;
    margin-bottom: 24px;
    animation: float 3s ease-in-out infinite;
  }
  
  .empty-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 12px 0;
  }
  
  .empty-description {
    font-size: 16px;
    color: #666;
    margin: 0 0 32px 0;
    max-width: 400px;
    line-height: 1.6;
  }
  
  .empty-actions {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  @keyframes float {
    0% {
      transform: translateY(0px);
    }
    50% {
      transform: translateY(-10px);
    }
    100% {
      transform: translateY(0px);
    }
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .empty-actions {
      flex-direction: column;
      gap: 12px;
      width: 100%;
    }
    
    .empty-actions .ant-btn {
      width: 100%;
    }
    
    .empty-icon {
      font-size: 60px;
    }
  }
</style>
